package cn.jsj.hzu.qm.facecloud.user.dao.impl;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.jsj.hzu.qm.facecloud.user.dao.UserDao;
import cn.jsj.hzu.qm.facecloud.user.pojo.User;

public class UserDaoImpl implements UserDao {

	JdbcTemplate jdbcTemplate = null;

	public int getUserMaxId() {
		String sql = "SELECT MAX(user_id) FROM tb_user";
		int i = jdbcTemplate.queryForObject(sql, Integer.class);
		return i;
	}

	// 1
	@Override
	public int addUser(User user) {

		int now_id = getUserMaxId() + 1;
		user.setUser_id(now_id);

		String sql_user = "INSERT INTO tb_user VALUES (? ?, ?,   ?, ?, ?,   NOW())";

		try {

			jdbcTemplate.update(sql_user, new Object[] { user.getUser_id(), user.getUser_password(),
					user.getUser_email(), user.getUser_memo(), 1, user.getUser_type() });

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;
	}

	@Override
	public int deleteUser(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updateUser(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public User findUserById(int id) {
		String sql = "SELECT * FROM tb_user WHERE id = ?";
		
		try {
			User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), new Object[] {id});
			return user;
		} catch (Exception e) {
			e.printStackTrace();
		}
		

		
		return null;
	}

	@Override
	public User findUserByEmail(String email) {
		String sql_query = "SELECT * FROM tb_user WHERE user_email=?";
		try {
			User user = (User) jdbcTemplate.queryForObject(sql_query, new BeanPropertyRowMapper<>(User.class),
				new Object[] { email });
			return user;
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return null;
	}

	public int findUserIdByEmail(String email) {
		return findUserByEmail(email).getUser_id();
	}

	@Override
	public List<User> findAllUsers() {
		String sql = "SELECT * FROM tb_user";
		
		try {
			List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
			return users;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("在查询所有用户时出现错误");
		}
		return null;
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	/**
	 * 获取所有用户的数量
	 * 
	 */
	public int getAllUserNum() {
		String sql = "SELECT COUNT(*) FROM tb_user";

		try {
			int i = jdbcTemplate.queryForObject(sql, Integer.class);
			return i;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return -1;
	}

}
